/*
 * Copyright (c) 2014, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.omorphdb.core.io;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;

/**
 * Extends the {@link Resource} class wrapping a local file.
 * 
 * @author Marco Tamburelli
 */
class LocalResource extends Resource implements Closeable
{
	private final File file;
	private final ResourceLimitProvider resourceLimitProvider;
	private final FileChannel channel;

	private final int pageSize;

	class ReaderImpl extends ReadPage implements Reader
	{
		ReaderImpl(FileChannel channel, int pageSize) throws IOException
		{
			super(channel, pageSize);
		}

		@Override
		public void setCursor(long position) throws IOException
		{
			setCursorPosition(position);
		}

		@Override
		public long getCursor() throws IOException
		{
			return getCursorPosition();
		}

		@Override
		public long shift(int amount) throws IOException
		{
			return moveCursor(amount);
		}

		@Override
		public void rewind() throws IOException
		{
			setCursorPosition(0);
		}

		@Override
		public String readString() throws IOException
		{
			return new String(readStringAsBytes());
		}

		@Override
		public byte[] readStringAsBytes() throws IOException
		{
			int length = readBytes(Constants.SIZEOF_INT).getInt();

			return readBytes(length).array();
		}

		@Override
		public double readDouble() throws IOException
		{
			return readBytes(Constants.SIZEOF_DOUBLE).getDouble();
		}

		@Override
		public float readFloat() throws IOException
		{
			return readBytes(Constants.SIZEOF_FLOAT).getFloat();
		}

		@Override
		public long readLong() throws IOException
		{
			return readBytes(Constants.SIZEOF_LONG).getLong();
		}

		@Override
		public int readInt() throws IOException
		{
			return readBytes(Constants.SIZEOF_INT).getInt();
		}

		@Override
		public short readShort() throws IOException
		{
			return readBytes(Constants.SIZEOF_SHORT).getShort();
		}

		@Override
		public char readChar() throws IOException
		{
			return readBytes(Constants.SIZEOF_CHAR).getChar();
		}

		@Override
		public byte readByte() throws IOException
		{
			return readBytes(Constants.SIZEOF_BYTE).get();
		}

		@Override
		public boolean readBoolean() throws IOException
		{
			return readBytes(Constants.SIZEOF_BYTE).get() != Constants.FALSE;
		}

		@Override
		public byte readType() throws IOException
		{
			return readByte();
		}

		private ByteBuffer readBytes(int size) throws IOException
		{
			byte[] bytes = new byte[size];

			get(bytes);

			return ByteBuffer.wrap(bytes);
		}
	}

	class WriterImpl extends WritePage implements Writer
	{

		WriterImpl(FileChannel channel, int pageSize) throws IOException
		{
			super(channel, pageSize);
		}

		@Override
		public void setCursor(long position) throws IOException
		{
			setCursorPosition(position);
		}

		@Override
		public long getCursor() throws IOException
		{
			return getCursorPosition();
		}

		@Override
		public long shift(int amount) throws IOException
		{
			return moveCursor(amount);
		}

		@Override
		public void rewind() throws IOException
		{
			setCursorPosition(0);
		}

		@Override
		public void writeString(String string) throws IOException
		{
			writeStringAsBytes(string.getBytes());
		}

		@Override
		public void writeStringAsBytes(byte[] bytes) throws IOException
		{
			int l = bytes.length;

			ByteBuffer buff = ByteBuffer.allocate(l + Constants.SIZEOF_INT);
			buff.putInt(l);
			buff.put(bytes);

			put(buff.array());
		}

		@Override
		public void writeDouble(double d) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_DOUBLE);
			buff.putDouble(d);

			put(buff.array());
		}

		@Override
		public void writeFloat(float f) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_FLOAT);
			buff.putFloat(f);

			put(buff.array());
		}

		@Override
		public void writeLong(long l) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_LONG);
			buff.putLong(l);

			put(buff.array());
		}

		@Override
		public void writeInt(int i) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_INT);
			buff.putInt(i);

			put(buff.array());
		}

		@Override
		public void writeShort(short s) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_SHORT);
			buff.putShort(s);

			put(buff.array());
		}

		@Override
		public void writeChar(char c) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_CHAR);
			buff.putChar(c);

			put(buff.array());
		}

		@Override
		public void writeByte(byte b) throws IOException
		{
			put(new byte[] { b });
		}

		@Override
		public void writeBoolean(boolean b) throws IOException
		{
			put(new byte[] { b ? Constants.TRUE : Constants.FALSE });
		}

		@Override
		public void writeType(byte type) throws IOException
		{
			writeByte(type);
		}
	}

	class AppenderImpl extends WritePage implements Appender
	{
		AppenderImpl(FileChannel channel, int pageSize, long resourceLimit) throws IOException
		{
			super(channel, resourceLimit, pageSize);
		}

		@Override
		public long getCursor() throws IOException
		{
			return getCursorPosition();
		}

		@Override
		public void appendString(String string) throws IOException
		{
			byte[] bytes = string.getBytes();
			appendStringAsBytes(bytes);
		}

		@Override
		public void appendStringAsBytes(byte[] bytes) throws IOException
		{
			int l = bytes.length;

			ByteBuffer buff = ByteBuffer.allocate(l + Constants.SIZEOF_INT);
			buff.putInt(l);
			buff.put(bytes);

			put(buff.array());
		}

		@Override
		public void appendDouble(double d) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_DOUBLE);
			buff.putDouble(d);

			put(buff.array());
		}

		@Override
		public void appendFloat(float f) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_FLOAT);
			buff.putFloat(f);

			put(buff.array());
		}

		@Override
		public void appendLong(long l) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_LONG);
			buff.putLong(l);

			put(buff.array());
		}

		@Override
		public void appendInt(int i) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_INT);
			buff.putInt(i);

			put(buff.array());
		}

		@Override
		public void appendShort(short s) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_SHORT);
			buff.putShort(s);

			put(buff.array());
		}

		@Override
		public void appendChar(char c) throws IOException
		{
			ByteBuffer buff = ByteBuffer.allocate(Constants.SIZEOF_CHAR);
			buff.putChar(c);

			put(buff.array());
		}

		@Override
		public void appendByte(byte b) throws IOException
		{
			put(new byte[] { b });
		}

		@Override
		public void appendBoolean(boolean b) throws IOException
		{
			put(new byte[] { b ? Constants.TRUE : Constants.FALSE });
		}

		@Override
		public void appendType(byte type) throws IOException
		{
			appendByte(type);
		}

		@Override
		public void reserve(int length) throws IOException
		{
			setCursorPosition(resourceLimitProvider.shiftResourceLimit(length));
		}
	}

	/**
	 * Constructor. It provides low level access to the data encoded a given
	 * file.
	 * 
	 * @param file The file to read/write/append low level information.
	 * @param pageSize The size of each page. Used to read and write.
	 * @throws IOException
	 */
	protected LocalResource(File file, int pageSize) throws IOException
	{
		Set<OpenOption> options = new HashSet<OpenOption>();
		options.add(StandardOpenOption.CREATE);
		options.add(StandardOpenOption.WRITE);
		options.add(StandardOpenOption.READ);

		this.file = file;
		this.resourceLimitProvider = new ResourceLimitProvider(this.file);
		this.channel = FileChannel.open(this.file.toPath(), options);
		this.pageSize = pageSize;
	}

	@Override
	public long getResourceLimit()
	{
		return this.resourceLimitProvider.getResourceLimit();
	}

	@Override
	public Reader createReader() throws IOException
	{
		return new ReaderImpl(this.channel, this.pageSize);
	}

	@Override
	public Writer createWriter() throws IOException
	{
		return new WriterImpl(this.channel, this.pageSize);
	}

	@Override
	public Appender createAppender() throws IOException
	{
		return new AppenderImpl(this.channel, this.pageSize, this.resourceLimitProvider.getResourceLimit());
	}

	@Override
	public boolean remove() throws IOException
	{
		this.channel.close();
		return this.file.delete();
	}

	@Override
	public void close() throws IOException
	{
		this.channel.close();
		this.resourceLimitProvider.close();
	}
}
